package cn.myjerry.server.demo1;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Server {
	private ServerSocket server;
	
	public static final String CRLF = "\r\n";
	public static final String BLANK = " ";
	
	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}
	
	public void start() {
		try {
			server = new ServerSocket(8888);
			
			this.receive();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void receive() {
		try {
			Socket client = server.accept();
			
			byte[] data = new byte[20480];
			
			int len = client.getInputStream().read(data);
			
			String requestInfo = new String(data, 0, len).trim();
			
			System.out.println(requestInfo);
			
			StringBuilder responseContext = new StringBuilder();
			responseContext.append("<html leng=\"en\"><head><meta charset=\"utf-8\"><title>策四</title></head><body>这是一条测试语句</body></html>");
			
			StringBuilder response = new StringBuilder();
			response.append("HTTP/1.1 200 OK").append(CRLF);
			response.append("Server: Jerry").append(CRLF);
			response.append("Date:").append(new Date()).append(CRLF);
			response.append("Content-Type: text/html;charset=UTF-8").append(CRLF);
			response.append("Content-Length:").append(responseContext.toString().getBytes().length).append(CRLF);
			response.append(CRLF);
			response.append(responseContext);
			
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
			
			bw.write(response.toString());
			bw.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void stop() {
		
	}
}
